var Q = require('q'),
	barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller');

//1,根据传入的barcode(eg:test12345)在条码主档表中找到条码主档ID
//2,在装配关系表中通过上步找到的条码主档ID==装配条码ID（AssemblyBarcode）
//，找到对应的条码主档ID（BarcodeMaster）
//3,获取芯片ID、出货批次、尺寸（扩展字段1）、物料号（关联物料档案获取）。


exports.getAssemblyBarcodeData = function(req, res) {
	var barcode = req.body.Parameter.Barcode;

	doAssemblyBarcodeData(barcode).then(function(result) {
		res.json(result);
	}, function(err) {
		res.json(err);
	});
};

//获取工位和作业信息
exports.getLocationAndWork = function(req, res) {
	var deviceId = req.body.Parameter.DeviceId;

	findLocationAndWork(deviceId).then(function(result) {
		res.json(result);
	}, function(err) {
		res.json(err);
	});
};


exports.doStocking = function(req, res) {
	//包装货号
	var packagecode = req.body.Parameter.Packagecode;
	//芯片ID集合
	var barcodes = req.body.Parameter.Barcodes;
	doDataStocking(packagecode, barcodes).then(function(result) {
		res.json(result);
	}, function(err) {
		res.json(err);
	});
};


function findLocationAndWork(deviceId) {
	var deferred = Q.defer();
	barcodeMasterController.findLocationAndWork(deviceId, function(err, record) {
		if (err) {
			deferred.reject(err);
			return;
		} else {
			if (record != null) {
				deferred.resolve(record);
			}

		}
	});

	return deferred.promise;
}

//入库（包装条码 物件条码集合（查找到的芯片id） 设备id）
function doDataStocking(packagecode, barcodeMasters, deviceId, deviceName, workId, workName, locationId, locationName, userId) {
	var deferred = Q.defer();
	var operation_Id = ''; //工序id
	var BizRecordIds = [];//流水ids
	barcodeMasterController.insertPackageBarcode(packagecode, function(err, barcodeMaster) {
		if (err) {
			deferred.reject(err);
			return;
		} else {
			if (barcodeMaster != null) {
				barcodeMasterController.updateBarcodes(barcodeMasters, function(err, record) {
					if (err) {
						deferred.reject(err);
						return;
					} else {
						if (record != null) {
							barcodeMasterController.insertBarcodesFlow(barcodeMasters, deviceId, deviceName, workId, workName, locationId, locationName, userId, function(err, record, operationId) {
								operation_Id = operationId;
								if (err) {
									deferred.reject(err);
									return;
								} else {
									if (record != null) {
										barcodeMasterController.insertPackageAssemblyRelation(packageBarcode, barcodeMasters, function(err, record) {
											if (err) {
												deferred.reject(err);
												return;
											} else {
												if (record != null) {
													barcodeMasterController.insertStockingRecord(barcodeMasters,userId, operation_Id,BizRecordIds, function(err, record) {
														console.log(record);
													});
												}

											}
										});
									}

								}
							});
						}

					}
				});
			}

		}
	});
	return deferred.promise;

}

//获取装配条码的信息
function doAssemblyBarcodeData(barcode) {
	var deferred = Q.defer();
	barcodeMasterController.findAssemblyBarcodeMasterId(barcode, function(err, barcodeMaster) {
		if (err) {
			deferred.reject(err);
			return;
		} else {
			if (barcodeMaster._id) {
				barcodeMasterController.findAssemblyBarcodeMaster(barcodeMaster._id, function(err, barcodeMaster) {
					if (err) {
						deferred.reject(err);
						return;
					}
					if (barcodeMaster == null) {
						var newErr = new Error();
						newErr.leval = 9;
						newErr.title = '条码扫描失败';
						newErr.message = '该条码没有对应的条码主档！';
						deferred.resolve({
							Data: null,
							Error: newErr
						});
					} else {
						var result = {
							_id: barcodeMaster.BarcodeMaster._id,
							Barcode: barcodeMaster.BarcodeMaster.Barcode,
							ItemMasterCode: barcodeMaster.BarcodeMaster.ItemMasterCode,
							ShipLotNumber: barcodeMaster.BarcodeMaster.ShipLotNumber
						};
						deferred.resolve({
							Data: result,
							Error: null
						});
					}
					// deferred.resolve(barcodeMaster);
				});
			}
		}
	});
	return deferred.promise;
};